package com.seupyy.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectResult;

import java.io.FileInputStream;
import java.io.InputStream;

public class AliOssUtil {
    public static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";

    public static final String OSS_ACCESS_KEY_ID = "LTAI5tFm9wKjA2B7YJFCumHh";
    public static final String OSS_ACCESS_KEY_SECRET = "n7Ui2M33OL5gvi0NlvMizJrZiO8zh4";

    public static final String BUCKET_NAME = "big-event-hxj";

    public static String uploadFile(String objectName, InputStream is) throws Exception {


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, OSS_ACCESS_KEY_ID, OSS_ACCESS_KEY_SECRET);
        String url = "";

        try {

            PutObjectResult result = ossClient.putObject(BUCKET_NAME, objectName, is);
            url = "https://" + BUCKET_NAME + "." + ENDPOINT.substring(ENDPOINT.lastIndexOf("/") + 1) + "/" + objectName;

        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
        } catch (ClientException ce) {
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return url;
    }
}
